package controllers.systemadmin

import javax.inject.Inject

import controllers.BaseController
import models.JsonFormatters.{jurisdictionFormatter, jurisdictionQueryFormatter}
import models.{Jurisdiction, JurisdictionQuery}
import repos.JurisdictionRepository

class JurisdictionController @Inject()(jurisdictionRepository: JurisdictionRepository) extends BaseController {

  import jurisdictionRepository.dbConfig.driver.api._

  import scala.concurrent.ExecutionContext.Implicits.global

  def list = jsonAction[JurisdictionQuery] {
    (param, request) => {
      jurisdictionRepository.filter(j => {
        param.id.map(j.id === _).getOrElse(LiteralColumn(true)) &&
          param.juriParentId.map(j.juriParentId === _).getOrElse(LiteralColumn(Option(true))) &&
          param.juriCode.map(j.juriCode === _).getOrElse(LiteralColumn(true)) &&
          param.juriName.map(j.juriName.like(_)).getOrElse(LiteralColumn(true))
      }, param.page.getOrElse(1), param.pageSize match {
        case Some(_) => param.pageSize
        case None => Option(25)
      }).map(r => {
        Map("success" -> true,
          "total" -> r._1,
          "data" -> r._2,
          "message" -> "list complete")
      })
    }
  }

  def find = jsonAction[JurisdictionQuery] {
    (param, request) => {
      jurisdictionRepository.getById(param.id.get).map(j => {
        Map("success" -> true,
          "message" -> "find complete",
          "data" -> j)
      })
    }
  }

  def add = authJsonAction[Jurisdiction](Array("admin")) {
    (param, request) => {
      jurisdictionRepository.save(param).map(j => {
        Map("success" -> true,
          "resultCode" -> 0,
          "message" -> "add complete",
          "data" -> j.id)
      })
    }
  }

  def remove = authJsonAction[JurisdictionQuery](Array("admin")) {
    (param, request) => {
      jurisdictionRepository.remove(param.id.get).map(j => {
        Map("success" -> true,
          "resultCode" -> 0,
          "message" -> "remove complete",
          "data" -> param)
      })
    }
  }

  def modify = authJsonAction[Jurisdiction](Array("admin")) {
    (param, req) => {
      jurisdictionRepository.update(param).map(j => {
        Map("success" -> true,
          "resultCode" -> 0,
          "message" -> "modify complete",
          "data" -> param.id)
      })
    }
  }
}
